package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.javabean.User;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = { "/files/*" })
public class LoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest sr = (HttpServletRequest) request;
		HttpSession session = sr.getSession(); // 获得session
		User user = (User) session.getAttribute("user");
		// 获锝当前的URL
		String strURL = sr.getRequestURL().toString();
		if ((strURL.indexOf("index_meeting2.jsp") != -1 || (strURL
				.indexOf("RL2.jsp") != -1))
				|| (strURL.indexOf("meetBooking2.jsp") != -1)
				|| (strURL.indexOf("MonthCheck") != -1)||(strURL.indexOf("UserDeal") != -1)) {
			chain.doFilter(request, response);
		} else {
			// 判断用户是否登录，如果没有，
			if ((user == null)) {
				// 判断是否为login.jsp,或者register.jsp
				if ((strURL.indexOf("login.jsp") == -1)
						&& (strURL.indexOf("login_meeting.jsp") == -1)
						&& (!strURL
								.matches("http:\\/\\/[^\\/]+\\/campus\\/files\\/UserDeal"))) {
					((HttpServletResponse) response).sendRedirect(sr
							.getContextPath() + "/files/login.jsp");
				} else {
					chain.doFilter(request, response);
				}
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {

	}

}
